class IncentivesController < ApplicationController

  def index
    @incentives = Incentive.find(:all, :order => "package_id, goal")
  end

  def picture
    @incentive = Incentive.find(params[:id])
        send_data(@incentive.data, 
             :filename => @incentive.name, 
             :type => @incentive.content_type, 
             :disposition => "inline") 
    
  end

  def show
    @incentive = Incentive.find(params[:id])
    return self.unauthorized unless self.current_user.can('view:incentives', @incentive)
    add_page_token(@incentive.reward)
  end

  def new
    @incentive = Incentive.new
  end

  def edit
    @incentive = Incentive.find(params[:id])
    return self.unauthorized unless self.current_user.can('edit:incentives', @incentive)
    add_page_token(@incentive.reward)
  end

  def create
    @incentive = Incentive.new(params[:incentive])
    return self.unauthorized unless self.current_user.can('create:incentives', @incentive)
    @incentive_image = IncentiveImage.new(:uploaded_data => params[:incentive_image_file]) 
    @service = IncentiveService.new(@incentive, @incentive_image) 

    respond_to do |format| 
      if @service.save
        flash[:notice] = 'Incentive was successfully created.' 
        format.html { redirect_to(@incentive) } 
        format.xml { render :xml => @incentive, 
        :status => :created, 
        :location => @incentive } 
      else 
        format.html { render :action => :new } 
        format.xml { render :xml => @incentive.errors, 
        :status => :unprocessable_entity } 
      end 
    end 
  end

  def update 
    @incentive = Incentive.find(params[:id]) 
    return self.unauthorized unless self.current_user.can('edit:incentives', @incentive)
    @incentive_image = @incentive.incentive_image 
    @service = IncentiveService.new(@incentive, @incentive_image) 
    respond_to do |format| 
      if @service.update_attributes(params[:incentives], params[:incentives_image_file]) 
        flash[:notice] = 'Incentive was successfully updated.' 
        format.html { redirect_to @incentive } 
        format.xml { head :ok } 
      else 
        @incentive_image = @service.incentive_image 
        format.html { render :action => :edit } 
        format.xml { render :xml => @incentive.errors, 
        :status => :unprocessable_entity } 
      end 
    end 
  end 


  def destroy
    @incentive = Incentive.find(params[:id])
    return self.unauthorized unless self.current_user.can('delete:incentives', @incentive)
    @incentive.destroy

    redirect_to incentives_path
  end

end
